package com.samsung.spen.sshare.main.history;

import java.util.ArrayList;
import java.util.Date;

import com.samsung.spen.sshare.R;
import com.samsung.spen.sshare.main.MainActivity;
import com.samsung.spen.sshare.main.UpdateViewHistory;
import com.samsung.spen.sshare.main.data.History;
import com.samsung.spen.sshare.main.data.HistoryColumns;
import com.samsung.spen.sshare.main.data.SshareDataService;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Contacts;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class HistoryFragment extends Fragment implements UpdateViewHistory {


	
	private int mNum;
	private ListView mListView = null;
	private MainActivity bindedActivity = null;

	private ArrayList<History> mHistories = new ArrayList<History>();
	private HistoryDataAdapter adapter;

	public HistoryFragment newInstance(int num) {
		HistoryFragment f = new HistoryFragment();

		Bundle args = new Bundle();
		args.putInt("num", num);
		f.setArguments(args);

		return f;
	}

	@Override
	public void onCreate(Bundle bundle) {
		super.onCreate(bundle);
		this.mNum = getArguments() != null ? getArguments().getInt("num") : 1;
		this.bindedActivity = (MainActivity) this.getActivity();
		setHasOptionsMenu(true);
	}
	
	@Override
	public void onAttach(Activity activity) {
		((MainActivity)getActivity()).updateViewHistory= this;
		super.onAttach(activity);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.main_activity_histories, container,
				false);
		getActivity().bindService(
				new Intent(getActivity(), SshareDataService.class),
				mConnection, Context.BIND_AUTO_CREATE);

		mListView = (ListView) v.findViewById(R.id.lv_history);
		adapter = new HistoryDataAdapter(getActivity());
		mListView.setAdapter(adapter);
		
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
					long arg3) {
				 Intent i = new Intent(getActivity(), HistoryDetailActivity.class);
				 i.putExtra(HistoryColumns.PHONE_NUMBER, mHistories.get(pos).getPhoneNumber());
			 	 startActivityForResult(i, 1);

			}
		});
		return v;
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (requestCode) {
		case HistoryDetailActivity.RESULT_CODE_DELETE_DETAIL:
			Log.d("BEBE", "result history fragment");
			mHistories = mService.getHistoryWithPhone();
			adapter.clear();
			adapter.addAll(mHistories);
			break;
			
		default:
			break;
		}

		super.onActivityResult(requestCode, resultCode, data);

	}

	@Override
	public void onActivityCreated(Bundle bundle) {
		super.onActivityCreated(bundle);
	}

	class HistoryDataAdapter extends ArrayAdapter<History> {

		public HistoryDataAdapter(Context context) {
			super(context, R.layout.main_listview_history_item, mHistories);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View row = convertView;
			DataHolder holder;
			if (row == null) {
				LayoutInflater inflater = bindedActivity.getLayoutInflater();
				row = inflater.inflate(R.layout.main_listview_history_item,
						parent, false);
				holder = new DataHolder(row);
				row.setTag(holder);
			} else {
				holder = (DataHolder) row.getTag();
			}
			holder.setData(mHistories.get(position));
			return row;
		}

	}

	class DataHolder {
		TextView tvContact, tvPhone, tvDateTime;
		ImageView ivDetails;

		public DataHolder(View view) {
			tvPhone = (TextView) view.findViewById(R.id.tv_phone);
			tvContact = (TextView) view.findViewById(R.id.tv_contact);
			tvDateTime = (TextView) view.findViewById(R.id.tv_date_time);
			ivDetails = (ImageView) view.findViewById(R.id.iv_details);
		}

		public void setData(History history) {
			tvPhone.setText(history.getPhoneNumber());
			Cursor cursor = getActivity().getContentResolver().query(android.provider.ContactsContract.Contacts.CONTENT_URI, null,android.provider.ContactsContract.Contacts.DISPLAY_NAME + "= ?",new String[] { history.getPhoneNumber() } , null);
			if(cursor.moveToFirst())
				tvContact.setText(cursor.getString(cursor.getColumnIndex(android.provider.ContactsContract.Contacts.DISPLAY_NAME)));
			else
			tvContact.setText("No Contact");
			tvDateTime.setText("Last time: "
					+ new Date(history.getDateTime()).toString());
		}
	}

	private SshareDataService mService;
	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;

		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = ((SshareDataService.SshareDataServiceBinder) service)
					.getService();
			Log.d("BEBE", "den day chua?1");

//			long i = mService.insertHistory("097567373", "404.34.34.346", "rjtdnfbh.jpg", "", 132533, 121212, 1);

			mHistories = mService.getHistoryWithPhone();
			for (History h : mHistories) {
				Log.d("BEBE", " history: " + h.getFileName());
			}

			adapter.clear();
			adapter.addAll(mHistories);

			getActivity().unbindService(mConnection);

		}
	};

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		inflater.inflate(R.menu.main_fragment_history, menu);
		super.onCreateOptionsMenu(menu, inflater);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_delete_all :
			int r = mService.deleteAllHistory();
			Log.d("BEBE", "delete row :" + r);
			mHistories = mService.getHistoryWithPhone();
			adapter.clear();
			adapter.addAll(mHistories);
			return true;

		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void updateHistoryFragment() {
		Log.d("BEBE", "update view bebe :");
		mHistories = mService.getHistoryWithPhone();
		adapter.clear();
		adapter.addAll(mHistories);
	}
}
